# -*- coding:utf-8 -*-

import urllib
import hashlib


def sign_with_query_items(data):
    udid = data['deviceId']
    # 将请求参数按key排序
    data = {k: data[k] for k in sorted(data.keys())}
    # 拼接成字符串
    data_str = ''
    for k, v in data.items():
        data_str += '{}={}'.format(k, v)
    data_str = urllib.parse.quote(data_str, 'utf-8')

    # 将url encode之后的字符串的每个字符与对应的udid字符进行异或原形
    xor_str = ''
    udid_length = len(udid)
    for i in range(len(data_str)):
        data_char = data_str[i]
        udid_index = int(i % udid_length)
        udid_char = udid[udid_index]
        rst = ord(udid_char) ^ ord(data_char)
        xor_str += str(rst)

    # 对异或后的字符串MD5
    md5 = hashlib.md5()
    md5.update(xor_str.encode())
    md5_str = md5.hexdigest()

    # 将MD5后的字符串和udid拼接起来，再次MD5
    md5_str += udid
    md5 = hashlib.md5()
    md5.update(md5_str.encode())
    md5_str = md5.hexdigest()
    return md5_str


if __name__ == '__main__':
    params = {
        "deviceId": "09c26e69-4dd3-3923-98e0-192bbb80103e",
        "device_fingerprint": "201910311912389a3f5a74e15c33655d76f5418a561bc001f3988f5a5bb100",
        "device_fingerprint1": "201910311912389a3f5a74e15c33655d76f5418a561bc001f3988f5a5bb100",
        "fid": "1575801853006cdd75295012140dbcde9eb9ec66a1bd",
        "lang": "zh-Hans",
        "page": "",
        "page_pos": "",
        "page_size": "",
        "platform": "",
        "sid": "",
        "sort": "",
        "source": "",
        "t": ""
    }
    print(sign_with_query_items(params))

import hashlib

Arr ={
    "platform":"android",
    "deviceId":"09c26e69-4dd3-3923-98e0-192bbb80103e",
    "device_fingerprint":"201910311912389a3f5a74e15c33655d76f5418a561bc001f3988f5a5bb100",
    "device_fingerprint1":"201910311912389a3f5a74e15c33655d76f5418a561bc001f3988f5a5bb100",
    "versionName":"6.35.0",
    "channel":"Guanfang",
    "sid":"session.1575801730382713578617",
    "lang":"zh-Hans",
    "t":"1582954287",
    "fid": "1575801853006cdd75295012140dbcde9eb9ec66a1bd",
}
def md5hex(word):
    m = hashlib.md5()
    m.update(word.encode("utf-8"))
    return m.hexdigest()

def sortedDictValues3(adict):
    keys = adict.keys()
    keys.sort
    return map(adict.get, keys)

def get_sign(Arr):
    Str=''
    Keys=sorted(Arr.keys())

    for item in Keys:
        if item!='':
            Str=Str+item+'%3D'+Arr[item]
    deviceId=Arr['deviceId']
    v1_2 = bytearray(Str, 'utf-8')
    v5_1 = ''
    v3_2 = 0
    v2 = 0
    v4_1=bytearray(deviceId, 'utf-8')

    while v2<len(v1_2):
        v5_1 = v5_1 + str(v1_2[v2] ^ v4_1[v3_2 ])
        v3_2 = (v3_2 + 1) % len(v4_1)
        v2 = v2 + 1

    sign=md5hex(md5hex(v5_1)+deviceId)
    return sign

print(get_sign(Arr))